package cn.sumpu.app.coolsk.web.util;

import java.util.LinkedList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fivestars.interfaces.bbs.client.Client;
import com.fivestars.interfaces.bbs.util.XMLHelper;

public class UCUtil {
	private final static Logger logger = LoggerFactory.getLogger(UCUtil.class);
	
	private static BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(
			100);
	private static ThreadPoolExecutor exec = new ThreadPoolExecutor(5, 10, 60,
			TimeUnit.SECONDS, queue);

	// 同步登录爽网
	public static void loginCoolgy(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String username = request.getParameter("loginName");
			String password = request.getParameter("loginPwd");
			if (null != username && null != password) {
				Client uc = new Client();
				String result = uc.uc_user_login(username, password);

				LinkedList<String> rs = XMLHelper.uc_unserialize(result);
				if (rs.size() > 0) {
					int $uid = Integer.parseInt(rs.get(0));
					String $username = rs.get(1);
					String $password = rs.get(2);
//					String $email = rs.get(3);
					if ($uid > 0) {
						response.addHeader(
								"P3P",
								" CP=\"CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR\"");

						// out.println("登录成功");
						// out.println($username);
						// out.println($password);
						// out.println($email);

						String $ucsynlogin = uc.uc_user_synlogin($uid);
						// out.println("登录成功"+$ucsynlogin);
						// out.println($ucsynlogin);
						request.getSession(true).setAttribute("ucsynlogin",
								$ucsynlogin);

						// 本地登陆代码
						// TODO ... ....

						Cookie auth = new Cookie("auth", uc.uc_authcode(
								$password + "\t" + $uid, "ENCODE"));
						auth.setMaxAge(31536000);
						// auth.setDomain("localhost");
						response.addCookie(auth);

						Cookie user = new Cookie("uchome_loginuser", $username);
						response.addCookie(user);

					} else if ($uid == -1) {
						// out.println("用户不存在,或者被删除");
						if (logger.isErrorEnabled()) {
							logger.error("[coolsk] sync login to [coolgy] fail: 用户不存在,或者被删除");
						}
					} else if ($uid == -2) {
						// out.println("密码错");
						if (logger.isErrorEnabled()) {
							logger.error("[coolsk] sync login to [coolgy] fail: 密码错");
						}
					} else {
						// out.println("未定义");
						if (logger.isErrorEnabled()) {
							logger.error("[coolsk] sync login to [coolgy] fail: 未定义");
						}
					}
				} else {
					// out.println("Login failed");
					// System.out.println(result);
					if (logger.isErrorEnabled()) {
						logger.error("[coolsk] sync login to [coolgy] fail: Login failed["+result+"]");
					}
				}
			}
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("[coolsk] sync login to [coolgy] fail: ", e);
			}
		}
	}

	// 同步登出爽网
	public static void logoutCoolgy(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			Client uc = new Client();

			// setcookie('Example_auth', '', -86400);
			// 生成同步退出的代码
			String $ucsynlogout = uc.uc_user_synlogout();
			// System.out.println("退出成功"+$ucsynlogout);
			request.getSession(true).setAttribute("ucsynlogout", $ucsynlogout);
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("[coolsk] sync logout to [coolgy] fail: ", e);
			}
		}
	}
	
	// 异步注册爽网
	public static void rsyncRegisterCoolgy(String username, String password,
			String email) {
		Future f = exec.submit(new UCUtil.Reg(username,password,email));
		try {
			f.get(10, TimeUnit.SECONDS);
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("[coolsk] sync register to [coolgy] fail: ",e);
			}
		}
	}

	static class Reg implements Runnable {

		String username;
		String password;
		String email;

		Reg(String username, String password,
				String email) {
			this.username = username;
			this.password = password;
			this.email = email;
		}

		@Override
		public void run() {
			registerCoolgy(username,password,email);
		}
	}

	// 注册爽网
	public static void registerCoolgy(String username, String password,
			String email) {
		try {
			Client uc = new Client();
			String $returns = uc.uc_user_register(username, password, email);
			int $uid = Integer.parseInt($returns);
			if ($uid <= 0) {
				if ($uid == -1) {
					if (logger.isErrorEnabled()) {
						logger.error("[coolsk] sync register to [coolgy] fail: 用户名不合法");
					}
				} else if ($uid == -2) {
					if (logger.isErrorEnabled()) {
						logger.error("[coolsk] sync register to [coolgy] fail: 包含要允许注册的词语");
					}
				} else if ($uid == -3) {
					if (logger.isErrorEnabled()) {
						logger.error("[coolsk] sync register to [coolgy] fail: 用户名已经存在");
					}
				} else if ($uid == -4) {
					if (logger.isErrorEnabled()) {
						logger.error("[coolsk] sync register to [coolgy] fail: Email 格式有误");
					}
				} else if ($uid == -5) {
					if (logger.isErrorEnabled()) {
						logger.error("[coolsk] sync register to [coolgy] fail: Email 不允许注册");
					}
				} else if ($uid == -6) {
					if (logger.isErrorEnabled()) {
						logger.error("[coolsk] sync register to [coolgy] fail: 该 Email 已经被注册");
					}
				} else {
					if (logger.isErrorEnabled()) {
						logger.error("[coolsk] sync register to [coolgy] fail: 未定义");
					}
				}
			} else {
				if (logger.isInfoEnabled()) {
					logger.info("[coolsk] sync register to [coolgy] ok: "
							+ $returns);
				}
			}
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("[coolsk] sync register to [coolgy] fail: ", e);
			}
		}
	}
	
	// just test
	public static void main(String[] args) {
		UCUtil.rsyncRegisterCoolgy("jojo", "31700891", "35692740@qq.com");
	}
}
